package com.sz.common.base.service;

import com.sz.common.base.cache.EntityCache;
import com.sz.common.base.dao.DaoSupport;
import com.sz.common.base.dao.Pagination;
import com.sz.common.base.dao.ParamData;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.exception.CommonErrorCodes;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.logger.Logger;
import com.sz.common.base.utils.EntityUtils;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.base.utils.UUIDGenerator;

import javax.annotation.Resource;
import java.util.Map;

/**
 * Function: AbstractService <br>
 * Author: Charles <br>
 * Date: 2016-12-01 15:13:00
 */
public abstract class AbstractService {
    /**
     * 日志记录器
     */
    protected Logger logger = Logger.getLogger(this.getClass());
    @Resource(name = "daoSupport")
    protected DaoSupport dao;

    protected String getMapperNamespace() {
        return "";
    }

    protected String getSqlName(String... shortName) {
        if (shortName == null || shortName.length == 0) {
            return "";
        }
        String ns = getMapperNamespace();
        StringBuilder sBuilder = new StringBuilder();
        if (StringUtils.hasLength(ns)) {
            sBuilder.append(ns).append(".");
        }
        for (String name : shortName) {
            sBuilder.append(name).append(".");
        }
        return sBuilder.substring(0, sBuilder.length() - 1); //remove last dot
    }

    /**
     * 清除命名空间下的entity缓存
     */
    protected void clearEntityCache() {
        EntityCache.clearNamespace(this.getMapperNamespace());
    }

    /**
     * @param params --页面参数
     * @return 查询参数
     */
    protected ParamData convertQueryParams(QueryParams params) {
        ParamData pd = new ParamData();
        if (StringUtils.hasLength(params.getLanguage())) {
            pd.put("language", params.getLanguage());
        }
        if (StringUtils.hasLength(params.getQuery())) {
            pd.put("query", params.getQuery());
        }

        Map<String, Object> mapParam = params.getParam();
        if (mapParam != null && mapParam.size() > 0) {
            for (Map.Entry<String, Object> entry : mapParam.entrySet()) {
                pd.put(entry.getKey(), entry.getValue());
            }
        }
        if (StringUtils.hasLength(params.getSort())) {
            if (!EntityUtils.isValidFieldName(params.getSort())) {
                throw Exceptions.bizException(CommonErrorCodes.ERROR_ARGUMENT_ILLEGAL, params.getSort());
            }
            pd.put("sort", params.getSort());
            if (params.isAsc()) { //有排序时才需要加asc与desc
                pd.put("order", "asc");
            } else {
                pd.put("order", "desc");
            }
        }

        Pagination page = new Pagination(params.getPageSize(), params.getPageIndex());
        pd.setPagination(page);
        return pd;
    }

    /**
     * 生成新的UUID主键
     *
     * @return
     */
    protected String generateNewUid() {
        return UUIDGenerator.generateOrderedUUID();
    }


    /**
     * 实体检查字符为空并且返回trim的字符串，str为空会抛参数为空的异常
     *
     * @param str
     * @param fieldName
     * @return
     */
    public static String getCheckedTrimString(String str, String fieldName) {
        if (str != null) {
            str = str.trim();
        }
        if (StringUtils.isEmpty(str)) {
            throw Exceptions.bizException(CommonErrorCodes.ERROR_ARGUMENT_EMPTY, fieldName);
        }
        return str;
    }

    public void checkCode(Integer id, String code) {
        ParamData pd = new ParamData();
        pd.put("id", id);
        pd.put("code", code);
        int count = (Integer) dao.findForObject(getSqlName("findCountByCode"), pd);
        if (count > 0) {
            throw Exceptions.bizException(CommonErrorCodes.ERROR_MODEL_CODE_EXIST, "");
        }
    }

}
